import { ref } from 'vue'
import { store } from '@/stores'
import { defineStore } from 'pinia'
import { ValueError } from '@jcstdio/jc-utils/exceptions'

const _useMaskStore = defineStore('web-mask', () => {
  const _showMask = ref(true)
  const defaultShowMaskIndex = ref<number | undefined>(undefined)
  const maskIndex = ref<number>(-1)
  const bgColor = ref('#cdcdcd')
  const opacity = ref(0.8)

  /**
   * 设置 遮盖层 的 层级 （z-index属性实现）
   * @param index 层级值
   */
  function setDefaultMaskIndex(index: number) {
    if (index < 1) {
      throw ValueError(`Param "value" must be greater than 1, while actually got ${index}.`)
    }
    defaultShowMaskIndex.value = index
  }

  /**
   * 显示 Mask
   * - 可以通过 setDefaultMaskIndex 方法改变显示的层级，默认层级为 15999999
   */
  function showMask() {
    if (defaultShowMaskIndex.value === undefined) {
      maskIndex.value = 15999999
    } else {
      maskIndex.value = defaultShowMaskIndex.value
    }
    _showMask.value = true
  }

  /**隐藏 Mask*/
  function hideMask() {
    maskIndex.value = -1
    _showMask.value = false
  }

  /**切换 Mask 显示状态 */
  function toggleMask() {
    if (_showMask.value) {
      hideMask()
    } else {
      showMask()
    }
  }

  /**
   * 设置遮盖物的背景色
   * @param color 颜色值，应该符合CSS颜色规范
   */
  function setMaskBgColor(color: string) {
    bgColor.value = color
  }

  /**
   * 设置 Mask 透明度
   * @param value 透明度的值，必须介于 0-1 之间
   */
  function setMaskOpacity(value: number) {
    if (value < 0 || value > 1) {
      throw ValueError(
        `Param "value" must be greater than 0 and less than 1, while actually got ${value}.`
      )
    }
    opacity.value = value
  }

  return {
    _showMask,
    maskIndex,
    bgColor,
    opacity,
    setDefaultMaskIndex,
    setMaskBgColor,
    showMask,
    hideMask,
    toggleMask,
    setMaskOpacity
  }
})

export function useMaskStore() {
  return _useMaskStore(store)
}
